import datetime
import time

import pandas as pd
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait

from compements.tool import process_date


def get_sf_data(driver, sf_time, skip, record):
    if skip:
        sf_data_collection = {}
        current_date = datetime.datetime.now()
        current_year = current_date.year

        try:
            # 找到包含 "2024" 的所有年份元素
            year_cells = WebDriverWait(driver, 5).until(ec.presence_of_all_elements_located(
                (By.XPATH, f'//td/div[text()="{current_year}"]')))
        except:
            return sf_data_collection

        # 假设 sf_time 是一个日期列表，已经和 year_cells 对应
        i = 0  # 初始化索引

        for year_cell in year_cells:
            driver.switch_to.default_content()
            # 切换到第一个 iframe
            first_iframe = WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen21"]/iframe')))
            driver.switch_to.frame(first_iframe)

            # 重新获取 year_cells 列表，并继续处理
            year_cells = WebDriverWait(driver, 5).until(ec.presence_of_all_elements_located(
                (By.XPATH, f'//td/div[text()="{current_year}"]')))

            # 获取年份元素的父级 <tr>，然后在该行内找到日期列
            # 确保在交互之前元素仍然有效，避免StaleElementReferenceException
            row = year_cell.find_element(By.XPATH, './ancestor::tr')
            date_cell = row.find_element(By.XPATH, './td[2]/div')  # 找到第二个 <td> 中的日期元素
            date_cell.click()

            # 切换到第二个 iframe
            second_iframe = WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen32"]/iframe')))
            driver.switch_to.frame(second_iframe)

            # 获取随访数据
            sf_data = {}

            # 收缩压
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="sbp"]')))
                sbp = element.get_attribute('value')
                sf_data['收缩压'] = sbp
            except:
                sf_data['收缩压'] = '未查'

            # 舒张压
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="dbp"]')))
                dbp = element.get_attribute('value')
                sf_data['舒张压'] = dbp
            except:
                sf_data['舒张压'] = '未查'

            # 空腹血糖
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="fbg"]')))
                FBG = element.get_attribute('value')
                sf_data['空腹血糖'] = FBG
            except:
                sf_data['空腹血糖'] = '未查'

            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="heartRateCur"]')))
                target_heart_rate = element.get_attribute('value')
                sf_data['心率'] = target_heart_rate
            except:
                sf_data['心率'] = '未查'

            # 餐后血糖
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="pbg"]')))
                PBG = element.get_attribute('value')
                sf_data['餐后血糖'] = PBG
            except:
                sf_data['餐后血糖'] = '未查'

            # 糖化血红蛋白
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="hba1c"]')))
                glycosylated_hemoglobin = element.get_attribute('value')
                sf_data['糖化血红蛋白'] = glycosylated_hemoglobin
            except:
                sf_data['糖化血红蛋白'] = '未查'

            # 当前体重
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="weightCur"]')))
                weightCur = element.get_attribute('value')
                sf_data['体重'] = weightCur
            except:
                sf_data['体重'] = '未查'

            # 确保sf_time是一个可迭代对象，如果它是单个时间戳，则转换为列表
            if isinstance(sf_time, pd.Timestamp):
                sf_time = [str(sf_time).replace(" 00:00:00", "")]

            # 将日期和随访数据保存到字典中
            if i < len(sf_time):
                sf_data_collection[sf_time[i]] = sf_data
                i += 1  # 更新索引
    else:
        print("随访日期读表")
        sf_data_collection = {}
        new_sf_time = process_date(record['随访日期'])
        new_year = new_sf_time.split('-')[0]
        print("需要新建随访的年份", new_year)

        try:
            # 找到包含 "2024" 的所有年份元素
            year_cells = WebDriverWait(driver, 5).until(ec.presence_of_all_elements_located(
                (By.XPATH, f'//td/div[text()="{new_year}"]')))
        except:
            return sf_data_collection

        year_element = WebDriverWait(driver, 5).until(ec.presence_of_element_located(
            (By.XPATH, f'//*[@id="ext-gen14-gp-year-{new_year}"]')))
        year_class = year_element.get_attribute('class')
        if year_class == 'x-grid-group':
            print("年份已展开")
        else:
            print("年份未展开，正在展开...")
            year_element.click()
            time.sleep(1)

        try:
            year_cells = WebDriverWait(driver, 5).until(ec.presence_of_all_elements_located(
                (By.XPATH, f'//td/div[text()="{new_year}"]')))
        except:
            return sf_data_collection

        # 假设 sf_time 是一个日期列表，已经和 year_cells 对应
        i = 0  # 初始化索引

        for year_cell in year_cells:
            driver.switch_to.default_content()
            # 切换到第一个 iframe
            first_iframe = WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen21"]/iframe')))
            driver.switch_to.frame(first_iframe)

            # 重新获取 year_cells 列表，并继续处理
            year_cells = WebDriverWait(driver, 5).until(ec.presence_of_all_elements_located(
                (By.XPATH, f'//td/div[text()="{new_year}"]')))

            # 获取年份元素的父级 <tr>，然后在该行内找到日期列
            # 确保在交互之前元素仍然有效，避免StaleElementReferenceException
            row = year_cell.find_element(By.XPATH, './ancestor::tr')
            date_cell = row.find_element(By.XPATH, './td[2]/div')  # 找到第二个 <td> 中的日期元素
            date_cell.click()

            # 切换到第二个 iframe
            second_iframe = WebDriverWait(driver, 10).until(
                ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen32"]/iframe')))
            driver.switch_to.frame(second_iframe)

            # 获取随访数据
            sf_data = {}

            # 收缩压
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="sbp"]')))
                sbp = element.get_attribute('value')
                sf_data['收缩压'] = sbp
            except:
                sf_data['收缩压'] = '未查'

            # 舒张压
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="dbp"]')))
                dbp = element.get_attribute('value')
                sf_data['舒张压'] = dbp
            except:
                sf_data['舒张压'] = '未查'

            # 空腹血糖
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="fbg"]')))
                FBG = element.get_attribute('value')
                sf_data['空腹血糖'] = FBG
            except:
                sf_data['空腹血糖'] = '未查'

            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="heartRateCur"]')))
                target_heart_rate = element.get_attribute('value')
                sf_data['心率'] = target_heart_rate
            except:
                sf_data['心率'] = '未查'

            # 餐后血糖
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="pbg"]')))
                PBG = element.get_attribute('value')
                sf_data['餐后血糖'] = PBG
            except:
                sf_data['餐后血糖'] = '未查'

            # 糖化血红蛋白
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="hba1c"]')))
                glycosylated_hemoglobin = element.get_attribute('value')
                sf_data['糖化血红蛋白'] = glycosylated_hemoglobin
            except:
                sf_data['糖化血红蛋白'] = '未查'

            # 当前体重
            try:
                element = WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                    (By.XPATH, '//*[@id="weightCur"]')))
                weightCur = element.get_attribute('value')
                sf_data['体重'] = weightCur
            except:
                sf_data['体重'] = '未查'

            # 确保sf_time是一个可迭代对象，如果它是单个时间戳，则转换为列表
            if isinstance(sf_time, pd.Timestamp):
                sf_time = [str(sf_time).replace(" 00:00:00", "")]

            # 将日期和随访数据保存到字典中
            if i < len(sf_time):
                sf_data_collection[sf_time[i]] = sf_data
                i += 1  # 更新索引

    return sf_data_collection
